package cc.magicjson.example.demo.baidu;

import java.util.Random;

public class MontyHallProblemByBaiDu3Point5 {

    private static final int PRIZE_BEHIND_DOOR = 1;
    private static final int GOAT_BEHIND_DOOR = 0;

    private int[] doors;
    private Random random;

    public MontyHallProblemByBaiDu3Point5() {
        doors = new int[3];
        random = new Random();
        initializeDoors();
    }

    public static void main(String[] args) {
        MontyHallProblemByBaiDu3Point5 problem = new MontyHallProblemByBaiDu3Point5();
        double winningPercentage = problem.calculateWinningProbability();
        System.out.println("The winning probability by switching doors is: " + winningPercentage + "%");
    }

    private void initializeDoors() {
        for (int i = 0; i < doors.length; i++) {
            doors[i] = GOAT_BEHIND_DOOR;
        }
        // Place the prize behind a random door
        doors[random.nextInt(doors.length)] = PRIZE_BEHIND_DOOR;
    }

    public int chooseDoor() {
        // Let the participant choose a door
        return random.nextInt(doors.length);
    }

    public int openGoatDoor(int chosenDoor) {
        // Open a door with a goat
        int openDoor = -1;
        for (int i = 0; i < doors.length; i++) {
            if (i != chosenDoor && doors[i] == GOAT_BEHIND_DOOR) {
                openDoor = i;
                break;
            }
        }
        if (openDoor == -1) {
            throw new IllegalStateException("Could not find a door with a goat.");
        }
        // Mark the door as opened
        doors[openDoor] = -1;
        return openDoor;
    }

    public int switchDoor(int initialChoice, int openGoatDoor) {
        // Find the remaining door to switch to
        for (int i = 0; i < doors.length; i++) {
            if (i != initialChoice && i != openGoatDoor && doors[i] != -1) {
                return i;
            }
        }
        throw new IllegalStateException("Could not find a door to switch to.");
    }

    public double calculateWinningProbability() {
        // Simulate the problem 100000 times to calculate the winning probability
        int wins = 0;
        for (int i = 0; i < 100000; i++) {
            initializeDoors(); // Reset the doors for each simulation
            int chosenDoor = chooseDoor();
            int openGoatDoor = openGoatDoor(chosenDoor);
            int switchDoor = switchDoor(chosenDoor, openGoatDoor);

            // Check if switching doors wins the prize
            if (doors[switchDoor] == PRIZE_BEHIND_DOOR) {
                wins++;
            }
        }
        return (double) wins / 100000 * 100; // Return the winning percentage
    }
}